package jpa.beans;

import javax.annotation.Resource;
import javax.ejb.*;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import jpa.entities.Bestelling;
import jpa.entities.BestellingPK;
import jpa.entities.ClientBestelling;
import jpa.entities.Product;
import jpa.interfaces.ProductBeanInterface;

/**
 * Message-Driven Bean implementation class for: BestelProducten
 * 
 */
@MessageDriven(mappedName = "mQueue")
public class BestelProducten implements MessageListener {
	@PersistenceContext
	EntityManager em;
	/**
	 * Default constructor.
	 */
	public BestelProducten() {
		// TODO Auto-generated constructor stub
	}

	@Resource
	private MessageDrivenContext mdc;

	public void onMessage(Message msg) {
		//System.out.println("Binnenkomend berichie dude: " + msg.toString());
		ObjectMessage om  = null;
		InitialContext context;
		System.out.println(msg.toString());
		try {
			
			om = (ObjectMessage) msg;
			context = new InitialContext();
			
			ClientBestelling cb = (ClientBestelling) om.getObject();
			String prodID = String.valueOf(cb.getProductId());
			BestellingPK pk = new BestellingPK();
			Bestelling b = new Bestelling();
			
			System.out.println("Binnenkomend prodID dude: " + prodID);
			
			
			pk.setAantal(cb.getAantal());
			pk.setBestId(createNewBestellingID());
			pk.setKlantId(cb.getKlantId());
			pk.setProductId(cb.getProductId());
			
			b.setId(pk);

			em.persist(b); 
			System.out.println("Product opgeslagen ");
			msg.acknowledge();
			om.acknowledge();
			writeConfirmation(pk);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			mdc.setRollbackOnly();
		} catch (Throwable th) {
			System.out.println(th.getMessage());
			th.printStackTrace();
		}
	}

	public void ejbRemove() throws EJBException {
		System.out.println(" ejbRemove()");
	}
	
	public long createNewBestellingID()
	{
		System.out.println("hoi");
		Query q = em.createQuery("SELECT p FROM Bestelling p",Bestelling.class);
		q.setFirstResult(q.getResultList().size()-1);
		System.out.println(q.getResultList().size());
		Bestelling id = (Bestelling)q.getSingleResult();
		System.out.println("verkegen id: "+id.getId().getBestId());
		long newId = id.getId().getBestId();
		newId++;
		System.out.println("Nieuwe ID: "+newId);
		
		return newId;
	}
	
	public void writeConfirmation(BestellingPK pk) throws Exception
	{
        String confirm = "Bestelling voor klant: "+pk.getKlantId()+" met bestelID: "+pk.getBestId()+" is opgeslagen in de database.@"+pk.getBestId();
		
        InitialContext ctx = new InitialContext();
		
        ConnectionFactory cf = (ConnectionFactory) ctx.lookup("bestelFactory");
		
		Queue	queue = (Queue) ctx.lookup("mConfirm");
		
		Connection con = cf.createConnection();
		
		Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		MessageProducer sender = session.createProducer(queue);
		
		ObjectMessage message = session.createObjectMessage(confirm);
		
		sender.send(message);
	}

}
